IF OBJECT_ID('fSegmentHasChildren') IS NOT NULL 
BEGIN 
    DROP FUNCTION fSegmentHasChildren
    IF OBJECT_ID('fSegmentHasChildren') IS NOT NULL
        PRINT '<<< FAILED DROPPING FUNCTION fSegmentHasChildren >>>'
    ELSE 
        PRINT '<<< DROPPED FUNCTION fSegmentHasChildren >>>'
END
GO
CREATE FUNCTION dbo.fSegmentHasChildren
	(
        @SegmentId   int = NULL
    ,   @IncludeDocs bit = 1
	)
RETURNS bit
AS
BEGIN
    DECLARE
        @Bit        AS bit
    ,   @ChildSegmentId AS int

    SET @Bit = 0

    IF EXISTS(SELECT * FROM Segment WHERE ParentSegmentId = @SegmentId)
    BEGIN

        SELECT @ChildSegmentId = SegmentId FROM Segment WHERE ParentSegmentId = @SegmentId

        IF EXISTS(SELECT * FROM Document WHERE SegmentId = @ChildSegmentId)
        BEGIN
            SET @Bit = 1
        END
    END

    IF @Bit = 0 AND @IncludeDocs = 1
    BEGIN
        IF EXISTS(SELECT * FROM Document WHERE SegmentId = @SegmentId)
        BEGIN
            SET @Bit = 1
        END
    END

RETURN @Bit
END
GO
GRANT EXECUTE ON fSegmentHasChildren TO public
GO
IF OBJECT_ID('fSegmentHasChildren') IS NOT NULL 
    PRINT '<<< CREATED FUNCTION fSegmentHasChildren >>>' 
ELSE 
    PRINT '<<< FAILED CREATING FUNCTION fSegmentHasChildren >>>' 
GO
